package com.example.agriculture.controller;


import com.example.agriculture.entity.*;
import com.example.agriculture.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("User")
public class FrontController {
    @Resource
    private UserInforService userInforService;
    @Resource
    private ProducerService producerService;

    @Resource
    private ProductTypeService productTypeService;
    @Resource
    private ProductService productService;

    @Resource
    private OrderFormService orderFormService;

    @Resource
    private ShoppingCartService shoppingCartService;

    //产品类型集合
    @GetMapping("/mushrooms")
    public ModelAndView mushrooms(Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("LEAD/user/mushrooms");
        Integer producttype = id;
        String state = "已上传";
        List<Product> products = productService.productDisplay(producttype, state);
        //在页面上展示商品类型
        List<Product> products1 = productTypeService.SelectAllProductTpyeById(producttype);
        System.out.println(products1);
        //查询所有的商品类型
        List<ProductType> productTypes = productTypeService.SelectAllProductTpye();
        System.out.println(productTypes);
        modelAndView.addObject("productTypes", productTypes);
        modelAndView.addObject("productsinfor", products);
        modelAndView.addObject("products1", products1);
        return modelAndView;
    }

    //产品类型集合详情
    @GetMapping("/detailedMushrooms")
    public ModelAndView detailedMushrooms(Integer id, Integer ids) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("LEAD/user/mushrooms_detailed");
        Product products = productService.queryById(id);
        List<ProductType> productTypes = productTypeService.SelectAllProductTpye();
        System.out.println(products);
        //往页面传入商品类型
        modelAndView.addObject("productTypes", productTypes);
        modelAndView.addObject("productsinfor", products);
        return modelAndView;
    }

    //从详情页面添加数据进入购物车
    @PostMapping("/addShopCart")
    @ResponseBody
    public Map addShopCart(Integer num, Integer productId, Integer producerId, HttpSession session, Float productPrice) {
        Map map = new HashMap();
        Float totalPrice = num * productPrice;
        UserInfor userInfor = (UserInfor) session.getAttribute("Userinfo");
        int userid = userInfor.getUserId();
        Date date = new Date();
        shoppingCartService.insertAllInfor(num, productId, producerId, userid, date, totalPrice);
        map.put("msg","添加成功");
        map.put("res",1);
        return map;
    }

    //主页面
    @GetMapping("/loginGet")
    public ModelAndView loginGet(Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("LEAD/user/index");
        //在页面上展示我的商品类型
        List<ProductType> productTypes = productTypeService.SelectAllProductTpye();
//        主页面展示
        List<Product> products = productService.LimitSelect(0, 3);
        List<Product> products2 = productService.LimitSelect(3, 3);

        System.out.println(productTypes);
        modelAndView.addObject("productTypes", productTypes);
        modelAndView.addObject("products", products);
        modelAndView.addObject("products2", products2);

        return modelAndView;
    }

    //购物车
    @GetMapping("/Ushoppingcart")
    public ModelAndView Ushoppingcart(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("LEAD/user/cart");
        UserInfor userInfor = (UserInfor) session.getAttribute("Userinfo");
        int Userid = userInfor.getUserId();
        List<ProductType> productTypes = productTypeService.SelectAllProductTpye();
        System.out.println(productTypes);
        List<ShoppingCart> shoppingCarts = shoppingCartService.SelectByUserId(Userid);
        modelAndView.addObject("shoppingCarts", shoppingCarts);
        modelAndView.addObject("productTypes", productTypes);
        return modelAndView;
    }
    //购物车的结算功能
    @PostMapping("/finishShopCarts")
    @ResponseBody
    public Map finishShopCarts(Integer productId,Integer count,Float productPrice,Float productPriceTotal,Integer shoppingCartId,Integer producerId,HttpSession session){
        System.out.println(productId+"+"+count+"+"+productPrice+"+"+productPriceTotal+"+"+shoppingCartId+"+"+producerId);
        Map<String,Object>map = new HashMap<>();
        UserInfor userInfor1 = (UserInfor) session.getAttribute("Userinfo");
        UserInfor userInfor = userInforService.queryById(userInfor1.getUserId());
        //用户的钱
        Float usermoney = (Float) userInfor.getUserMoney();
        //购物车单个商品的总价
        Float shoppingTatalPrice = productPriceTotal;
        if (usermoney<shoppingTatalPrice){
            map.put("msg","资金不够");
            map.put("res",0);
            return map;
        }else {
            OrderForm orderForm = new OrderForm();
            Date date= new Date();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            CharSequence format = simpleDateFormat.format(date);
            orderForm.setOrderTime(date);
            Product p = new Product();
            p.setProductId(productId);
            orderForm.setProduct(p);
            orderForm.setUserInfor(userInfor1);
            orderForm.setCount(count);
            orderForm.setPriceTotal(productPriceTotal);
            orderForm.setOrderstate("待收货");
            //种植户的钱
            Producer producer = producerService.queryById(producerId);
            Float  ProducerMoney = (Float) producer.getProducerMoney();
            //商品的数量
            Product product = productService.queryById(productId);
            int  ProductTotal = product.getProductTotal();
            if (count<ProductTotal){
                //种植户的钱增加
                ProducerMoney = ProducerMoney+shoppingTatalPrice;
                Producer producer1 = new Producer();
                producer1.setProducerMoney(ProducerMoney);
                producer1.setProducerId(producerId);
                System.out.println(producer1);
                Producer producer2 = producerService.update(producer1);
                System.out.println(producer2);
                //用户的钱减少
                usermoney = usermoney-shoppingTatalPrice;
                UserInfor userInfor2 = new UserInfor();
                userInfor2.setUserMoney(usermoney);
                userInfor2.setUserId(userInfor1.getUserId());
                userInforService.update(userInfor2);
                //产品数量减少
                ProductTotal = ProductTotal - count;
                Product product1 = new Product();
                product1.setProductId(productId);
                product1.setProductTotal(ProductTotal);
                productService.update(product1);

                OrderForm insert = orderFormService.insert(orderForm);
                shoppingCartService.deleteById(shoppingCartId);
                map.put("msg","购买成功");
                map.put("res",1);
                return map;
            }
            map.put("msg","数量不够");
            map.put("res",0);
            return map;

        }
    }

    //删除购物车
    @GetMapping("/UDelShoppingcart")
    @ResponseBody
    public Map<String, Object> UDelShoppingcart(Integer id) {
        boolean b = shoppingCartService.deleteById(id);
        Map<String, Object> map = new HashMap<>();
            if (b) {
                map.put("res", "ok");
                map.put("msg", "删除该商品成功");
                return map;
            }
            map.put("res", "false");
            map.put("msg", "删除失败");
            return map;
}
    //在详情页直接购买
    @PostMapping("/ToOrder")
    @ResponseBody
    public Map ToOrder(Integer productId, HttpSession session,Integer num,Integer producerId,Float productPrice){
        System.out.println("++++++++++++++++++++++");
        Map<String,Object> map = new HashMap<>();
        UserInfor userInfor = (UserInfor) session.getAttribute("Userinfo");
        Product productbefore = productService.queryById(productId);
        Producer producer = producerService.queryById(producerId);
        //查看种植户的money
        Float producermoney = (Float) producer.getProducerMoney();
        Integer uid= userInfor.getUserId();
        UserInfor userInforsele =userInforService.queryById(uid);
        //之前的商品总数
//        Integer OLDNUM = productbefore.getProductTotal();
        //查看用户购买之前的钱
        Float usermoney = (Float) userInforsele.getUserMoney();
        //所购买的商品总价格
        Float pricetotal= productPrice * num;

        if (num > productbefore.getProductTotal()){
            map.put("msg","商品库存数量不足，不能购买！");
            map.put("res",0);
            return map;
        }

        if (usermoney < pricetotal){
            map.put("msg","钱包金额不足无法购买！");
            map.put("res",0);
            return map;
        }
        //用户钱包剩余金额
        Float userMoney = usermoney - pricetotal;
        //商户钱包可用金额
        Float producerMoney = producermoney + pricetotal;
        //商品剩余数量
        Integer productTotal = productbefore.getProductTotal() - num;
        OrderForm orderForm = new OrderForm();
        Date date = new Date();
        orderForm.setOrderTime(date);
        orderForm.setOrderstate("待收货");
        Product product = new Product();
        product.setProductId(productId);
        orderForm.setProduct(product);
        orderForm.setUserInfor(userInfor);
        orderForm.setCount(num);
        orderForm.setPriceTotal(pricetotal);
        orderFormService.insert(orderForm);
        Integer userId = userInfor.getUserId();
        userInforService.upUserMoney(userId,userMoney);
        producerService.upProducerMoney(producerId,producerMoney);
        productService.upProductTotal(productId,productTotal);
        map.put("msg","购买成功");
        map.put("res",1);
        return map;

    }
    //删除所有的购物车
    @GetMapping("/UDelShoppingcartAll")
    @ResponseBody
    public Map<String, Object> UDelShoppingcartAll(Integer id) {
        boolean b = shoppingCartService.deleteByUserId(id);
        Map<String, Object> map = new HashMap<>();
        if (b) {
            map.put("res", "ok");
            map.put("msg", "删除购物车成功");
            return map;
        }
        map.put("res", "false");
        map.put("msg", "删除失败");
        return map;
    }

    //个人中心
    @GetMapping("/Upersonal_center")
    public ModelAndView Upersonal_center(HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("LEAD/user/personal_center");
        List<ProductType> productTypes = productTypeService.SelectAllProductTpye();
        System.out.println(productTypes);
        modelAndView.addObject("productTypes",productTypes);
        String state = "待收货";
        String state2 = "已收货";
        UserInfor userInfor = (UserInfor) session.getAttribute("Userinfo");
        int userid = userInfor.getUserId();
        int count = orderFormService.selectState(state,userid);
        int count2 = orderFormService.selectState(state2,userid);
        modelAndView.addObject("count",count);
        modelAndView.addObject("count2",count2);
        return (modelAndView);
    }
    //我的订单
    @GetMapping("/Myorderq")
    public ModelAndView Myorderq(HttpSession session,Integer userid ){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("LEAD/user/myorderq");
        UserInfor userInfor = (UserInfor) session.getAttribute("Userinfo");
        userid = userInfor.getUserId();
        List<OrderForm> orderForms = orderFormService.queryByUserId(userid);
        System.out.println(orderForms);
        List<ProductType> productTypes = productTypeService.SelectAllProductTpye();
        modelAndView.addObject("productTypes",productTypes);
        modelAndView.addObject("orderForms",orderForms);
        return modelAndView;
    }
    //（确认收货）
    @PostMapping("/delOrder")
    @ResponseBody
    public Map<String, Object> UdelOrder(Integer orderId,String state) {
//        boolean b = orderFormService.deleteById(id);
//        System.out.println(state);
        System.out.println(orderId+"  "+state);
        state = "已收货";
//        OrderForm orderForm = new OrderForm();
//        orderForm.setOrderId(orderId);
//        orderForm.setOrderstate(state);
//        OrderForm orderForm1 = orderFormService.update(orderForm);
//        System.out.println(orderForm1);
        int count = orderFormService.updateOrderfor(state,orderId);
        System.out.println(count);

        Map<String, Object> map = new HashMap<>();
        if (count==1) {
            map.put("res", "ok");
            map.put("msg", "收获成功");
            return map;
        }
        map.put("res", "false");
        map.put("msg", "收获失败，请再次提交请求");
        return map;
    }
    //退款功能
    @PostMapping("/backMoney")
    @ResponseBody
    public Map<String, Object> backMoney(HttpSession session,Integer orderId,Integer count,Float princeTotal,Integer producerId,Integer productId) {
        Map<String, Object> map = new HashMap<>();
        //查询种植户的资金
        Producer producer = producerService.queryById(producerId);
        Float producerMoney = (Float) producer.getProducerMoney();
        OrderForm orderForm1 = orderFormService.queryById(orderId);
        if (orderForm1.getAgree()=="同意"){
            if (producerMoney>=princeTotal) {
                map.put("res", "ok");
                map.put("msg", "退款成功");
                //更新种植户的钱
                producerMoney = producerMoney - princeTotal;
                Producer producer1 = new Producer();
                producer1.setProducerId(producerId);
                producer1.setProducerMoney(producerMoney);
                producerService.update(producer1);
                //更新用户的钱
                UserInfor userInfor = (UserInfor) session.getAttribute("Userinfo");
                Float userMoney = (Float) userInfor.getUserMoney();
                userMoney = userMoney + princeTotal;
                UserInfor userInfor1 = new UserInfor();
                userInfor1.setUserId(userInfor.getUserId());
                userInfor1.setUserMoney(userMoney);
                userInforService.update(userInfor1);
                //商品数量的增加
                Product product = productService.queryById(productId);
                int productCount = product.getProductTotal();
                productCount = productCount + count;
                Product product1 = new Product();
                product1.setProductId(productId);
                product1.setProductTotal(productCount);
                productService.update(product1);
                //删除订单表
                OrderForm orderForm = new OrderForm();
                orderForm.setOrderstate("已退款");
                orderForm.setOrderId(orderId);
                orderFormService.update(orderForm);
                return map;
            }
        }
        OrderForm orderForm = new OrderForm();
        orderForm.setOrderstate("等待审核");
        orderForm.setOrderId(orderId);
        orderFormService.update(orderForm);
        map.put("res", "false");
        map.put("msg", "申请提交成功");
        return map;
    }
//取消退款
    @PostMapping("/cancel")
    @ResponseBody
    public Map<String, Object> cancel(Integer orderId) {
        Map<String, Object> map = new HashMap<>();
        OrderForm orderForm = new OrderForm();
        orderForm.setOrderstate("待收货");
        orderForm.setOrderId(orderId);
        orderFormService.update(orderForm);
        map.put("res", "1");
        map.put("msg", "成功取消退款");
        return map;
    }


    //个人信息
    @GetMapping("/Upersonalinfor")
    public ModelAndView Upersonalinfor(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("LEAD/user/personal_infor");
        List<ProductType> productTypes = productTypeService.SelectAllProductTpye();
        System.out.println(productTypes);
        modelAndView.addObject("productTypes",productTypes);
        return (modelAndView);
    }
    //修改密码
    @GetMapping("/Uchangepassword")
    public ModelAndView Uchangepassword(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("LEAD/user/change_password");
        List<ProductType> productTypes = productTypeService.SelectAllProductTpye();
        System.out.println(productTypes);
        modelAndView.addObject("productTypes",productTypes);
        return (modelAndView);
    }
    //忘记密码
    @GetMapping("/Uforget")
    public String Uforget(){
        return ("LEAD/user/forget");
    }

    //用户登录
    @GetMapping("/loginUser")
    public String Login123(){
        return "LEAD/user/login";
    }



//    //用户编辑个人信息
//    @GetMapping("/userUpdata")
//    public String userUpdata(){
//        return "LEAD/user/user_updata";
//    }
    //用户编辑个人信息
    @GetMapping("/UUserupdata")
    public ModelAndView UUserupdata(HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("LEAD/user/user_updata");
        UserInfor userInfor = (UserInfor) session.getAttribute("Userinfo");
        Integer userid = userInfor.getUserId();
        UserInfor userInfor1 =  userInforService.queryById(userid);
        modelAndView.addObject("userInfor",userInfor1);
        return modelAndView;
    }
    @PostMapping("/UPostAUserupdata")
    public String PostAUserupdata(UserInfor userInfor){
        userInforService.update(userInfor);
//        return "redirect:/User/Upersonalinfor";
        return "redirect:loginUser";

    }
    @PostMapping("/UchangPwd")
    @ResponseBody
    public Map PostAUserChangPwd(HttpSession session,String pwd, String pwd1,String code){
        System.out.println(pwd+","+pwd1+","+code);
        Map<String,Object> map = new HashMap<>();
        UserInfor userInfor = new UserInfor();
        UserInfor userinfo = (UserInfor) session.getAttribute("Userinfo");
        Object verifyCode = session.getAttribute("verifyCode");
        System.out.println(verifyCode.equals(code));
        if (verifyCode.equals(code)) {
            if (pwd.equals(userinfo.getUserPassword())) {
                userInfor.setUserId(userinfo.getUserId());
                userInfor.setUserPassword(pwd1);
                userInforService.update(userInfor);
                map.put("msg", "修改成功");
                return map;
            } else {
                map.put("msg", "和原密码不一样");
                return map;
            }
        }
        map.put("msg", "验证码不正确");
        return map;
    }
  @RequestMapping("/userforgetpassword")
  @ResponseBody
  public Map userforgetpassword(String userNumber,String code,HttpSession session){
     System.out.println(userNumber+"&&&&&"+code);
     Map<String,Object> map = new HashMap<>();
     String verifyCode = (String) session.getAttribute("verifyCode");
     String userPassword = "123456";
    if (verifyCode.equalsIgnoreCase(code)) {
        int count = userInforService.selectByUserId(userNumber);
        System.out.println(count);
        if (count !=0 ) {
            userInforService.updatePassword(userNumber,userPassword);
            map.put("msg", "密码重置成功！新密码为：123456");
            return map;
        } else {
            map.put("msg", "和原昵称不一样");
            return map;
        }
    }
    map.put("msg", "验证码不正确");
    return map;


}

    @PostMapping("/loginGet")
    public String getLogin123(String user_number, String user_password, HttpSession session){
        UserInfor query = userInforService.query(user_number, user_password);
        session.setAttribute("Userinfo",query);
        System.out.println(query);

        if(query!=null){
            return "redirect:loginGet";
        }else {
            return "redirect:loginUser";
        }

    }
    //用户注册
    @GetMapping("/register")
    public String register(){
        return "/LEAD/user/reg";
    }

    @PostMapping("/registeruser")
    public String getregister(UserInfor userInfor){
        UserInfor query = userInforService.query(userInfor.getUserNumber(), userInfor.getUserPassword());
        System.out.println(query);
        if(query ==null){
            int reg = userInforService.userin(userInfor);
            System.out.println(userInfor);
            if (reg!=0){
                return "LEAD/user/login";
            }
        }
        return "/LEAD/user/reg";
    }

    //退出登录
    @GetMapping("backUserLogin")
    public ModelAndView backLogin(HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:loginUser");
        session.invalidate();
        return modelAndView;
    }
}
